import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
import router_static_html
import router_module    
from config import *

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 根据配置决定是否挂载静态文件目录
    if enable_static_files:
        print(f"挂载静态文件目录: {static_files_directory} -> {static_files_url}")
        app.mount(static_files_url, StaticFiles(directory=static_files_directory), name="static")
    else:
        print("静态文件目录挂载已禁用")
        
    yield
    # 关闭时的清理代码可以放在这里

# 创建FastAPI应用
app = FastAPI(
    title=app_name,
    description=app_description,
    version=app_version,
    lifespan=lifespan
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源，生产环境中应该设置为特定的域名
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有头
)

# API前缀，用于所有API路由
API_PREFIX = "/api"

# 包含路由
app.include_router(router_module.router_module_real, prefix=f"{API_PREFIX}{router_dict['router_module']}")
app.include_router(router_static_html.router_html_real, prefix=f"{API_PREFIX}{router_dict['router_html']}")

# 添加根路径重定向到主页
@app.get("/")
async def root():
    from fastapi.responses import RedirectResponse
    # 如果静态文件目录已挂载，重定向到静态页面，否则重定向到API文档
    if enable_static_files:
        return RedirectResponse(url=f"{static_files_url}/index.html")
    else:
        return RedirectResponse(url="/docs")

# 添加API文档路径
@app.get("/api-docs")
async def api_docs():
    from fastapi.responses import RedirectResponse
    return RedirectResponse(url="/docs")

if __name__ == "__main__":
    # 启动FastAPI服务
    uvicorn.run(app, host=app_host, port=app_port) 
